// import 'promise-polyfill';
// import 'isomorphic-fetch';
import { h, render } from 'preact';
import { createStore } from 'redux';
import { Provider } from 'preact-redux';
import { parse } from 'query-string';
import reducer from '~/reducers/user';
import { authUrl } from '~/config';
import history from '~/core/history';
import Request from '~/core/request';

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
	window.alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
    + ' Column: ' + column + ' StackTrace: ' +  errorObj);
};

const url = window.location.href.split('?');
const search = parse(window.location.search);
let enter = [];
if (search.state) {
	enter = search.state .split('_');
}

function onloadCheck() {
	if (search.jwt) {
		window.sessionStorage.setItem('jwt', search.jwt);
		if (search.state) {
			if (enter[0] === 'invite') {
				// history.push(`/invitation?id=${enter[1]}`);
				window.location.href = `${url[0]}#/invitation?id=${enter[1]}`;
			} else if (enter[0] === 'share') {
				// history.push(`/card?cookId=${enter[1]}`);
				window.location.href = `${url[0]}#/card?cookId=${enter[1]}`;
			} else {
				// history.push('/');
				window.location.href = url[0];
			}
			console.log('search.state', search.state);
		} else {
			window.location.href = url[0];
		}
	}

	if (!window.sessionStorage.jwt) {
		if (enter[0] === 'invite') {
			window.location.href = `${authUrl}?state=invite_${enter[1]||null}`;
		} else if (enter[0] === 'share') {
			window.location.href = `${authUrl}?state=share_${enter[1]||null}`;
		} else {
			window.location.href = `${authUrl}?state=index_`;
		}
	}
}
// 发生跳转时浏览器会终止某些正在加载的资源，但又记录了这些资源的缓存信息
// 解决这个问题只要，确保所有资源完全被引用后再发生授权重定向检查即可
// 否则浏览器的某些缓存机制会遗漏资源，比如iOS的Safari对字体图标的缓存
window.onload = setTimeout(() => {onloadCheck();}, 100);


Request.configs.headers.Authorization = `Bearer ${window.sessionStorage.jwt}`;

let root;
const store = createStore(reducer);
function init() {
	let App = require('./components/App').default;
	root = render(<Provider store={store}><App /></Provider>, document.body, root);
}

// register ServiceWorker via OfflinePlugin, for prod only:
// if (process.env.NODE_ENV==='production') {
// 	require('./pwa');
// }

// in development, set up HMR:
if (module.hot) {
	//require('preact/devtools');   // turn this on if you want to enable React DevTools!
	module.hot.accept('./components/App', () => requestAnimationFrame(init) );
}

init();
